<!--
 * @Descripttion: 编辑活动
 * @Author: xiao li
 * @Date: 2020-07-06 12:17:07
 * @LastEditors: xiao li
 * @LastEditTime: 2022-01-20 19:28:50
-->
<template>
  <div>
    <top-nav :title="navTitle" :isBack="true"></top-nav>
    <div class="page-main">
      <el-form
        @submit.native.prevent
        :model="subForm"
        :rules="subFormRules"
        ref="subForm"
        label-width="140px"
      >
        <el-form-item label="活动名" prop="title">
          <el-input
            v-model="subForm.title"
            placeholder="请输入活动名"
          ></el-input>
        </el-form-item>
        <el-form-item label="分类" prop="classify_id">
          <el-select v-model="subForm.classify_id" placeholder="请选择">
            <el-option
              v-for="item in classifyOptions"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="封面图" prop="cover">
          <lb-cover
            :fileList="subForm.cover"
            @selectedFiles="getCover"
          ></lb-cover>
          <lb-tool-tips>图片建议尺寸: 750 * 400</lb-tool-tips>
        </el-form-item>
        <el-form-item label="轮播图片" prop="carousel">
          <lb-cover
            type="more"
            :fileList="subForm.carousel"
            @selectedFiles="selectedFiles($event, 'carousel')"
            @moveFiles="moveFiles($event, 'carousel')"
          ></lb-cover>
          <lb-tool-tips>图片建议尺寸: 750 * 750</lb-tool-tips>
        </el-form-item>
        <el-form-item label="报名人数" prop="sign_limit">
          <el-input-number
            class="lb-input-number"
            v-model="subForm.sign_limit"
            :controls="false"
            :precision="0"
            :min="0"
            placeholder="请输入报名人数"
          ></el-input-number>
          <lb-tool-tips>允许报名的人数</lb-tool-tips>
        </el-form-item>
        <el-form-item label="详情图片" prop="detail_images">
          <lb-cover
            type="more"
            :fileList="subForm.detail_images"
            @selectedFiles="selectedFiles($event, 'detail_images')"
            @moveFiles="moveFiles($event, 'detail_images')"
          ></lb-cover>
          <lb-tool-tips>图片建议尺寸: 750 * n</lb-tool-tips>
        </el-form-item>
        <el-form-item label="报名时间" prop="signTime">
          <el-date-picker
            v-model="subForm.signTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="活动时间" prop="activityTime">
          <el-date-picker
            v-model="subForm.activityTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="所属公司" prop="company_id">
          <el-cascader
            v-model="subForm.company_id"
            collapse-tags
            :options="base_company"
            @change="choiceAllCompanyItem"
            :props="{
              multiple: true,
              checkStrictly: true,
              label: 'name',
              value: 'id'
            }"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="报名内容" prop="items">
          <el-select
            v-model="subForm.items"
            multiple
            collapse-tags
            placeholder="请选择"
          >
            <el-option
              v-for="item in contentOptions"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="活动地址" prop="address">
          <el-input
            v-model="subForm.address"
            placeholder="请输入活动地址"
          ></el-input>
        </el-form-item>
        <el-form-item label="经度" prop="longitude">
          <el-input
            v-model="subForm.longitude"
            placeholder="请输入经度"
          ></el-input>
        </el-form-item>
        <el-form-item label="纬度" prop="latitude">
          <el-input
            v-model="subForm.latitude"
            placeholder="请输入纬度"
          ></el-input>
          <lb-button @click="showMap = true" type="primary" plain size="mini"
            >获取经纬度</lb-button
          >
        </el-form-item>
        <el-form-item label="活动介绍" prop="content_text">
          <lb-ueditor
            v-model="subForm.content_text"
            :destroy="true"
          ></lb-ueditor>
          <!-- <el-input type='textarea' :rows="4" v-model="subForm.text_desc" placeholder="请输入活动介绍"></el-input> -->
        </el-form-item>
        <el-form-item>
          <lb-button type="primary" @click="submitFormInfo('subForm')">{{
            $t('action.submit')
          }}</lb-button>
          <lb-button @click="$router.back(-1)">{{
            $t('action.back')
          }}</lb-button>
        </el-form-item>
      </el-form>
    </div>
    <lb-map :dialogVisible.sync="showMap" @selectedLatLng="getLatLng"></lb-map>
  </div>
</template>

<script>
import {
  reg
} from '@/utils/reg'
export default {
  data () {
    return {
      navTitle: '',
      classifyOptions: [],
      contentOptions: [],
      showMap: false,
      base_company: [],
      companyResult: [],
      form: {
        copyCompanyId: []
      },
      subForm: {
        id: '',
        title: '',
        classify_id: '',
        cover: [],
        sign_limit: 1,
        carousel: [],
        detail_images: [],
        signTime: '', // 报名时间
        activityTime: '', // 活动时间
        start_time: '',
        end_time: '',
        sign_start_time: '',
        sign_end_time: '',
        company_id: [],
        items: [],
        address: '',
        text_desc: '',
        content_text: '',
        longitude: '',
        latitude: ''
      },
      subFormRules: {
        title: { required: true, type: 'string', message: '请输入活动名', trigger: 'blur' },
        classify_id: { required: true, type: 'number', message: '请选择分类', trigger: 'change' },
        cover: { required: true, type: 'array', message: '请上传图片', trigger: 'change' },
        sign_limit: { required: true, type: 'number', validator: reg.isNum, trigger: 'blur' },
        // sign_limit: {required: true, type: 'number', message: '请输入报名人数', trigger: 'blur'},
        carousel: { required: true, type: 'array', message: '请上传图片', trigger: 'change' },
        // detail_images: {required: true, type: 'array', message: '请上传图片', trigger: 'change'},
        signTime: { required: true, type: 'array', message: '请选择时间', trigger: 'change' },
        activityTime: { required: true, type: 'array', message: '请选择时间', trigger: 'change' },
        company_id: { required: true, type: 'array', message: '请选择所属公司', trigger: 'change' },
        items: { required: true, type: 'array', message: '请选择报名内容', trigger: 'change' },
        address: { required: true, type: 'string', message: '请输入地址', trigger: 'blur' },
        text_desc: { required: true, type: 'string', message: '请输入活动介绍', trigger: 'blur' },
        content_text: { required: true, type: 'string', message: '请输入活动介绍', trigger: 'blur' },
        longitude: { required: true, message: '请输入经纬度', trigger: ['change', 'blur'] },
        latitude: { required: true, message: '请输入经纬度', trigger: ['change', 'blur'] }
      }
    }
  },
  async created () {
    let { id } = this.$route.query
    this.navTitle = this.$t(id ? 'menu.EditActivity' : 'menu.AddActivity')
    if (id) {
      await this.getDetail(id)
    }
    await this.getBaseCompany()
    this.getClassifyOptions()
    this.getContentOptions()
  },
  methods: {
    async getDetail (id) {
      let { code, data } = await this.$api.getActivityInfo({ id })
      if (code === 200) {
        let company = data.company_id || []
        let copyCompany = JSON.parse(JSON.stringify(company))
        let resCompany = copyCompany.length === this.companyResult.length ? [
          [0], ...copyCompany
        ] : copyCompany
        this.form.copyCompanyId = resCompany
        data.company_id = resCompany
        for (let key in this.subForm) {
          this.subForm[key] = data[key]
          this.subForm.cover = [{ url: data.cover }]
          this.subForm.carousel = data.carousel.map(item => {
            return { url: item }
          })
          if (data.detail_images.length > 0) {
            this.subForm.detail_images = data.detail_images.map(item => {
              return { url: item }
            })
          }
        }
        this.subForm.activityTime = [this.handleMomentTime(data.start_time), this.handleMomentTime(data.end_time)]
        this.subForm.signTime = [this.handleMomentTime(data.sign_start_time), this.handleMomentTime(data.sign_end_time)]
      }
    },
    async getBaseCompany () {
      // 基本信息验证
      let { data: company } = await this.$api.getBaseCompany()
      this.handleCompanyOptions(company)
      company.length &&
        company.unshift({
          id: 0,
          name: '全选'
        })
      if (this.subForm.id) {
        company.map(item => {
          item.disabled = true
          if (item.children && item.children.length > 0) {
            item.children.map(aitem => {
              aitem.disabled = true
            })
          }
        })
      }
      this.base_company = company
    },
    handleCompanyOptions (data, arr = []) {
      for (let i = 0, len = data.length; i < len; i++) {
        let newArr = JSON.parse(JSON.stringify(arr))
        newArr.push(data[i].id)
        this.companyResult.push(JSON.parse(JSON.stringify(newArr)))
        if (data[i].children && data[i].children.length) {
          this.handleCompanyOptions(data[i].children, newArr)
        }
      }
    },
    /**
     * @method 全选公司
     */
    choiceAllCompanyItem (val) {
      let { companyResult } = this
      // true = 添加  false 取消、减少
      let rType = val.length > this.form.copyCompanyId.length
      let firstVal = val[0] && val[0][0]
      if (rType) {
        // 添加
        if (firstVal && val.length === companyResult.length) {
          // 其他都选完了，就只有全选没选了
          this.subForm.company_id = [[0], ...val]
        } else if (firstVal === 0) {
          this.subForm.company_id = [[0], ...companyResult]
        }
      } else {
        // 减少
        if (firstVal === 0) {
          // 第一个为0 只取消全选
          let copyArr = JSON.parse(JSON.stringify(val))
          copyArr.splice(0, 1)
          this.subForm.company_id = copyArr
        } else if (val.length === companyResult.length) {
          // 清空
          this.subForm.company_id = []
        } else {
          this.subForm.company_id = val
        }
      }
      this.form.copyCompanyId = this.subForm.company_id
    },
    submitFormInfo (name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          let subForm = JSON.parse(JSON.stringify(this.subForm))
          subForm.cover = subForm.cover[0] ? subForm.cover[0].url : ''
          let carouselArr = subForm.carousel.map(item => { return item.url })
          subForm.carousel = carouselArr.join(';')
          if (subForm.detail_images.length > 0) {
            let imagesArr = subForm.detail_images.map(item => { return item.url })
            subForm.detail_images = imagesArr.join(';')
          } else {
            subForm.detail_images = ''
          }
          subForm.is_public = subForm.company_id[0][0] === 0 ? 1 : 0
          if (subForm.company_id[0][0] === 0) {
            subForm.company_id.splice(0, 1)
          }
          subForm.start_time = this.handleTimes(subForm.activityTime[0])
          subForm.end_time = this.handleTimes(subForm.activityTime[1])
          subForm.sign_start_time = this.handleTimes(subForm.signTime[0])
          subForm.sign_end_time = this.handleTimes(subForm.signTime[1])
          subForm.items = subForm.items.join(',')
          let urlType = subForm.id ? 'editActivityInfo' : 'addActivityInfo'
          this.$api[urlType](subForm).then(res => {
            if (res.code === 200) {
              this.$message.success(this.$t('tips.successSub'))
              this.$router.back(-1)
            }
          })
        }
      })
    },
    getCover (img) {
      this.subForm.cover = img
    },
    selectedFiles (imgs, key) {
      this.subForm[key].push(...imgs)
    },
    moveFiles (imgs, key) {
      this.subForm[key] = imgs
    },
    handleMomentTime (time) {
      return new Date(time * 1000)
    },
    handleTimes (time) {
      return parseInt(new Date(time).getTime() / 1000)
    },
    getClassifyOptions () {
      this.$api.getActivityListAllForSelect().then(res => {
        if (res.code === 200) {
          this.classifyOptions = res.data
        }
      })
    },
    getContentOptions () {
      this.$api.getActivityAllNoPage().then(res => {
        if (res.code === 200) {
          this.contentOptions = res.data
        }
      })
    },
    /**
     * @method 获取经纬度
     */
    getLatLng (latLng) {
      this.subForm.latitude = latLng.lat
      this.subForm.longitude = latLng.lng
    }
  }
}
</script>

<style lang="scss" scoped>
.page-main {
  .el-input,
  .lb-input-number,
  .el-cascader,
  .el-select {
    width: 300px;
  }
  .el-textarea {
    width: 600px;
  }
}
</style>
